package love.unknown.servlets;

import love.unknown.fruit.dao.FruitDao;
import love.unknown.fruit.dao.impl.FruitDAOImpl;
import love.unknown.fruit.pojo.Fruit;
import love.unknown.myssm.myspingmvc.ViewBaseServlet;
import love.unknown.myssm.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/index")
public class IndexServlet extends ViewBaseServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Integer pageNo = 1;
        HttpSession session = req.getSession();

        String oper = req.getParameter("oper");
        //若oper!=null 说明 通过表单的查询按钮点击过来
        //若oper==null 说明 不是通过查询按钮过来的

        String keyword = null;
        if (StringUtil.isNotEmpty(oper)&&"search".equals(oper)){
            //此时是通过查询发送来的请求
            //此时pageNo为1 keyword为请求参数获取
            pageNo = 1;
            keyword = req.getParameter("keyword");
            if (StringUtil.isEmpty(keyword)){
                keyword="";
            }
            session.setAttribute("keyword",keyword);
        }else {
            String pageNoStr = req.getParameter("pageNo");
            if (StringUtil.isNotEmpty(pageNoStr)){
                pageNo = Integer.parseInt(pageNoStr);
            }
            Object keywordObj = session.getAttribute("keyword");
            if (keywordObj!=null){
                keyword = (String)keywordObj;
            }else {
                keyword = "";
            }
        }





        session.setAttribute("pageNo",pageNo);

        FruitDao fruitDao = new FruitDAOImpl();
        List<Fruit> fruitList = fruitDao.getFruitList(keyword,pageNo);
        System.out.println(keyword);
        //保存到session作用域
        session.setAttribute("fruitList",fruitList);

        int fruitCount = fruitDao.getFruitCount(keyword);
        int pageCount = (fruitCount+5-1)/5;
        session.setAttribute("pageCount",pageCount);
        super.processTemplate("index",req,resp);
    }
}
